import java.lang.invoke.SwitchPoint;

/**
 * @author Yin_JC
 * @PackageName:PACKAGE_NAME
 * @Class:Product
 * @Description:
 * @date 2020/3/3 5:55
 */
class Clerk{
    private int production = 0;
    public synchronized void increase(){
        if(production<20){
            production ++;
            System.out.println(Thread.currentThread().getName()+"生产第"+production+"件商品");
            notify();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public synchronized void decrease(){
        if(production>0){
            System.out.println(Thread.currentThread().getName()+"消费第"+production+"件商品");
            production--;
            notify();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Product implements Runnable{
    private Clerk clerk;
    public Product(Clerk clerk){
        this.clerk = clerk;
    }


    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"开始生产");
        while (true) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.increase();
        }
    }
}

class Resume implements Runnable{
    private Clerk clerk;
    public Resume(Clerk clerk){
        this.clerk = clerk;
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"开始消费");
        while (true) {
            try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.decrease();
        }
    }
}





public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Product p = new Product(clerk);
        Resume r = new Resume(clerk);
        Thread t1 = new Thread(p);
        Thread t2 = new Thread(r);
        Thread t3 = new Thread(r);
        t1.setName("生产者1");
        t2.setName("消费者1");
        t3.setName("消费者2");
        t1.start();
        t2.start();
        t3.start();
    }
}
